#define  _CRT_SECURE_NO_WARNINGS 1
#include "list.h"
LTNode* LTInit()
{
	LTNode* phead = BuyListNode(-1);
	phead->next = phead;
	phead->prev = phead;

	return phead;
}

void LTDestroy(LTNode* phead)
{
	assert(phead);
	LTNode* tail = phead->next;

	while (tail!=phead)
	{
		LTNode* hnext = tail->next;
		free(tail);
		tail = hnext;
	}
	free(phead);
}

LTNode* LTfind(LTNode* phead, LTDataType x)
{
	assert(phead);
	LTNode* cur = phead->next;

	while (cur->data != x)
	{
		cur = cur->next;
	}

	return cur;
}


void LTPrint(LTNode* head)
{
	assert(head);
	LTNode* cur = head->next;
	while (cur != head)
	{
		printf("%d ", cur->data);
		cur = cur->next;
	}

}

bool LTEmpty(LTNode* phead)
{
	assert(phead);

	return phead->next = phead;
}

LTNode* BuyListNode(LTDataType x)
{
	LTNode* head = (LTNode*)malloc(sizeof(LTNode));
	if (head == NULL)
	{
		perror("malloc fail");
		return NULL;
	}
	head->data = x;
	head->next =NULL;
	head->prev = NULL;
	return head;
}

void LTPushfront(LTNode* phead, LTDataType x)
{
	assert(phead);
	/*LTNode* newnode = BuyListNode(x);
	LTNode* cur = phead->next;

	phead->next = newnode;
	newnode->prev = phead;
	newnode->next = cur;
	cur->prev = newnode;*/
	LTInsert(phead->next, x);
}

void LTPushback(LTNode* phead, LTDataType x)
{
	assert(phead);
	/*LTNode* newnode = BuyListNode(x);
	LTNode* cur = phead->prev;

	cur->next = newnode;
	newnode->prev = cur;
	newnode->next = phead;
	phead->prev = newnode;*/
	LTInsert(phead, x);
}

void LTPopback(LTNode* phead)
{
	assert(phead);
	assert(LTEmpty(phead));

	LTNode* cur = phead->prev;
	LTNode* tail = cur->prev;

	tail->next = phead;
	phead->prev = tail;
	free(cur);
	cur = NULL;

}

void LTPopfront(LTNode* phead)
{
	assert(phead);
	assert(LTEmpty(phead));

	LTNode* cur = phead->next;
	LTNode* tail = cur->next;

	phead->next = tail;
	tail->prev = phead;
	free(cur);
	cur = NULL;
}

void LTInsert(LTNode* pos, LTDataType x)
{
	assert(pos);
	LTNode* newnode = BuyListNode(x);
	LTNode* hprev = pos->prev;

	hprev->next = newnode;
	newnode->prev = hprev;
	newnode->next = pos;
	pos->prev = newnode;
}

void LTErase(LTNode* pos)
{
	assert(pos);
	LTNode* hprev = pos->prev;
	LTNode* hnext = pos->next;

	hprev->next = hnext;
	hnext->prev = hprev;
	free(pos);
	pos = NULL;
}